package com.sshop.core.controller;

import cn.itcast.common.page.Pagination;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.sshop.common.encode.Md5Pwd;
import com.sshop.common.web.ResponseUtils;
import com.sshop.common.web.session.SessionProvider;
import com.sshop.core.bean.country.City;
import com.sshop.core.bean.country.Province;
import com.sshop.core.bean.country.Town;
import com.sshop.core.bean.user.Addr;
import com.sshop.core.bean.user.Buyer;
import com.sshop.core.query.country.CityQuery;
import com.sshop.core.query.country.ProvinceQuery;
import com.sshop.core.query.country.TownQuery;
import com.sshop.core.query.order.OrderQuery;
import com.sshop.core.query.user.AddrQuery;
import com.sshop.core.query.user.BuyerQuery;
import com.sshop.core.service.country.CityService;
import com.sshop.core.service.country.ProvinceService;
import com.sshop.core.service.country.TownService;
import com.sshop.core.service.order.OrderService;
import com.sshop.core.service.user.AddrService;
import com.sshop.core.service.user.BuyerService;
import com.sshop.core.web.Constants;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 跳转登陆页面
 * 登陆
 * 个人资料
 * 收货地址
 *
 * @author lijiming
 */
@Controller
public class ProfileController {

    @Autowired
    private SessionProvider sessionProvider;
    @Autowired
    private Md5Pwd md5Pwd;
    @Autowired
    private BuyerService buyerService;
    @Autowired
    private ImageCaptchaService imageCaptchaService;
    @Autowired
    private OrderService orderService;

    //GET
    @RequestMapping(value = "/shopping/login.shtml", method = RequestMethod.GET)
    public String login() {
        return "buyer/login";
    }
    //POST

    /**
     * 1:验证码是否为null
     * 2:验证码  是否正确
     * 3:用户是否为NUll
     * 4:密码是否为NUll
     * 5:用户是否正确
     * 6密码是否正确
     * Md5  纯生Md5
     * 放进Session   跳转ReturnUrl
     *
     * @param buyer
     * @param captcha
     * @param returnUrl
     * @return
     */
    @RequestMapping(value = "/shopping/login.shtml", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
    public String login(Buyer buyer, String captcha, String returnUrl, ModelMap model, HttpServletRequest request, HttpServletResponse response) {
        //验证码是否为null
        if (StringUtils.isNotBlank(captcha)) {
            //1:JSESSIONID
            //2验证码
            if (imageCaptchaService.validateResponseForID(sessionProvider.getSessionId(request, response), captcha)) {
                if (null != buyer && StringUtils.isNotBlank(buyer.getUsername())) {
                    if (StringUtils.isNotBlank(buyer.getPassword())) {
                        Buyer b = buyerService.getBuyerByKey(buyer.getUsername());
                        if (null != b) {
                            //
                            if (b.getPassword().equals(md5Pwd.encode(buyer.getPassword()))) {
                                //把用户对象放在Session
                                sessionProvider.setAttribute(request, response, Constants.BUYER_SESSION, b);
                                if (StringUtils.isNotBlank(returnUrl)) {
                                    return "redirect:" + returnUrl;
                                } else {
                                    if ("admin".equals(buyer.getUsername())) {
                                        return "redirect:/index.do";
                                    }
                                    //个人中心
                                    return "redirect:/buyer/index.shtml";
                                }
                            } else {
                                model.addAttribute("error", "password error");
                            }
                        } else {
                            model.addAttribute("error", "username error");
                        }
                    } else {
                        model.addAttribute("error", "please input password");
                    }
                } else {
                    model.addAttribute("error", "please input username");
                }
            } else {
                model.addAttribute("error", "verification code error");
            }
        } else {
            model.addAttribute("error", "please input verification code");
        }
        return "buyer/login";
    }

    //个人中心
    @RequestMapping(value = "/buyer/index.shtml")
    public String index(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer pageNo) {
        Buyer buyer = (Buyer) sessionProvider.getAttribute(request, response, Constants.BUYER_SESSION);
        String userid = buyer.getUsername();
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.setBuyerId(userid);
        orderQuery.setPageSize(3);
        orderQuery.setPageNo(Pagination.cpn(pageNo));
        orderQuery.orderbyOid(false);
        Pagination pagination = orderService.getOrderListWithPage(orderQuery);
        pagination.pageView("/buyer/index.shtml", "");
        model.addAttribute("pagination", pagination);
        return "buyer/index";
    }

    //个人资料
    @RequestMapping(value = "/buyer/profile.shtml")
    public String profile(HttpServletRequest request, ModelMap model, HttpServletResponse response) {
        //加载用户
        Buyer buyer = (Buyer) sessionProvider.getAttribute(request, response, Constants.BUYER_SESSION);
        Buyer b = buyerService.getBuyerByKey(buyer.getUsername());
        model.addAttribute("buyer", b);
        //省
        List<Province> provinces = provinceService.getProvinceList(null);
        model.addAttribute("provinces", provinces);
        //市
        CityQuery cityQuery = new CityQuery();
        cityQuery.setProvince(b.getProvince());
        List<City> citys = cityService.getCityList(cityQuery);
        model.addAttribute("citys", citys);
        //县
        TownQuery townQuery = new TownQuery();
        townQuery.setCity(b.getCity());
        List<Town> towns = townService.getTownList(townQuery);
        model.addAttribute("towns", towns);

        return "buyer/profile";
    }

    //
    @RequestMapping(value = "/buyer/city.shtml")
    public void city(String code, HttpServletResponse response) {
        CityQuery cityQuery = new CityQuery();
        cityQuery.setProvince(code);
        List<City> citys = cityService.getCityList(cityQuery);

        JSONObject jo = new JSONObject();
        jo.put("citys", citys);
        ResponseUtils.renderJson(response, jo.toString());

    }

    @RequestMapping(value = "/buyer/town.shtml")
    public void town(String code, HttpServletResponse response) {
        TownQuery townQuery = new TownQuery();
        townQuery.setCity(code);
        List<Town> towns = townService.getTownList(townQuery);
        JSONObject jo = new JSONObject();
        jo.put("towns", towns);
        ResponseUtils.renderJson(response, jo.toString());

    }

    //收货地址
    @RequestMapping(value = "/buyer/deliver_address.shtml")
    public String address(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap, String error) {
        Buyer buyer = (Buyer) sessionProvider.getAttribute(request, response, Constants.BUYER_SESSION);
        AddrQuery addrQuery = new AddrQuery();
        addrQuery.setBuyerId(buyer.getUsername());
        List<Addr> addrs = addrService.getAddrList(addrQuery);
        //省
        List<Province> provinces = provinceService.getProvinceList(null);
        modelMap.addAttribute("provinces", provinces);
        modelMap.addAttribute("addrs", addrs);
        modelMap.addAttribute("buyer", buyer);
        modelMap.addAttribute("error", error);
        return "buyer/deliver_address";
    }

    @ResponseBody
    @RequestMapping(value = "/buyer/delAddr.shtml")
    public String delAddr(Integer id) {
        Integer n = addrService.deleteByKey(id);
        if (n >= 1) {
            return "delete success!";
        }
        return "delete fail!";
    }

    @RequestMapping(value = "/buyer/change_password.shtml")
    public String toPassword() {
        return "/buyer/change_password";
    }

    @ResponseBody
    @RequestMapping(value = "/buyer/password.shtml")
    public String password(String realPassword, HttpServletRequest request, HttpServletResponse response) {
        Buyer b = (Buyer) sessionProvider.getAttribute(request, response, Constants.BUYER_SESSION);
        if (b.getPassword().equals(md5Pwd.encode(realPassword))) {
            b.setPassword(md5Pwd.encode(realPassword));
            buyerService.updateBuyerByKey(b);
        } else {
            return "password error！";
        }
        return "update success!";
    }

    @RequestMapping(value = "/shopping/logout.shtml")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        sessionProvider.logout(request, response);
        return "redirect:/shopping/login.shtml";
    }

    @ResponseBody
    @RequestMapping(value = "/shopping/register.shtml", method = RequestMethod.POST)
    public String register(Buyer buyer, String captcha, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isBlank(captcha)) {
            return "please input verification code";
        }
        if (!imageCaptchaService.validateResponseForID(sessionProvider.getSessionId(request, response), captcha)) {
            return "verification code error";
        }
        if (StringUtils.isBlank(buyer.getUsername())) {
            return "please input username";
        }
        BuyerQuery buyerQuery = new BuyerQuery();
        buyerQuery.setUsername(buyer.getUsername());
        List<Buyer> buyerList = buyerService.getBuyerList(buyerQuery);
        if (buyerList != null && buyerList.size() > 0) {
            return "username already exist in system";
        }
        if (StringUtils.isBlank(buyer.getPassword())) {
            return "please input password";
        }
        buyer.setPassword(md5Pwd.encode(buyer.getPassword()));
        buyer.setRegisterTime(new Date());
        buyer.setIsDel(1);
        buyerService.addBuyer(buyer);
        return "register success";
    }

    @RequestMapping("/buyer/orders.shtml")
    public String orders() {
        return "buyer/index";
    }

    @ResponseBody
    @RequestMapping("/buyer/updateBuyer.shtml")
    public String updateBuyer(Buyer buyer, HttpServletRequest request, HttpServletResponse response) {
        Buyer b = (Buyer) sessionProvider.getAttribute(request, response, Constants.BUYER_SESSION);
        b.setIsDel(buyer.getIsDel());
        b.setCity(buyer.getCity());
        b.setTown(buyer.getTown());
        b.setAddr(buyer.getAddr());
        b.setProvince(buyer.getProvince());
        b.setRealName(buyer.getRealName());
        b.setGender(buyer.getGender());
        buyerService.updateBuyerByKey(b);
        return "update success";
    }

    @RequestMapping("/buyer/updateAddr.shtml")
    public String updateAddr(Addr addr, HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        try {
            Buyer buyer = (Buyer) sessionProvider.getAttribute(request, response, Constants.BUYER_SESSION);
            String province1 = request.getParameter("province");
            String city1 = request.getParameter("city");
            String town1 = request.getParameter("town");
            ProvinceQuery provinceQuery = new ProvinceQuery();
            provinceQuery.setCode(province1);
            provinceQuery.setFields("name");
            String province = provinceService.getProvinceList(provinceQuery).get(0).getName();
            CityQuery cityQuery = new CityQuery();
            cityQuery.setCode(city1);
            cityQuery.setFields("name");
            String tCity = cityService.getCityList(cityQuery).get(0).getName();
            TownQuery townQuery = new TownQuery();
            townQuery.setCode(town1);
            townQuery.setFields("name");
            String town = townService.getTownList(townQuery).get(0).getName();
            String isDef = request.getParameter("isDef");
            if (isDef != null && !"".equals(isDef)) {
                addr.setIsDef(1);
            } else {
                addr.setIsDef(0);
            }
            String city = province + tCity + town;
            addr.setBuyerId(buyer.getUsername());
            addr.setCity(city);
            addrService.addAddr(addr);
            modelMap.addAttribute("error", "save success!");
        } catch (Exception e) {
            modelMap.clear();
            modelMap.addAttribute("error", "please check your input,try again");
        }
        return "redirect:/buyer/deliver_address.shtml";
    }
    @Autowired
    private ProvinceService provinceService;
    @Autowired
    private CityService cityService;
    @Autowired
    private TownService townService;
    @Autowired
    private AddrService addrService;
}
